<template>
  <div class="container">
    <!-- <el-card id="table-head-block">
      <b>工时填写</b>
    </el-card>-->
    <el-card id="table-block">
      <!-- <div slot="header"
           id="table-head-block"
           class="clearfix">
        <b>工时填写</b>
      </div>-->
      <div class="block">
        <!-- <span class="demonstration">日期</span>
        <p>{{chosenDate}}</p>-->
        <span>时间</span>
        <el-date-picker v-model="chosenDate"
                        type="week"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        placeholder="选择日期"
                        :picker-options="pickerOptions"
                        @change="pickerChange"></el-date-picker>
        <wt-button type="primary"
                   @click="onSubmit()">提交</wt-button>
        <el-popover placement="right"
                    width="140"
                    trigger="click">
          <el-button type="text"
                     class="more-btn"
                     @click="exportExcel">
            点击导出
            <i class="el-icon-download el-icon--right"></i>
          </el-button>
          <br />
          <br />
          <el-button type="text"
                     class="more-btn"
                     @click="showCharts = true">
            数据分析
            <i class="el-icon-s-data el-icon--right"></i>
          </el-button>
          <el-button type="text"
                     slot="reference">更多...</el-button>
        </el-popover>
      </div>

      <el-table id="table"
                :data="tableData"
                height="700"
                style="width: 100%">
        <el-table-column label="项目"
                         style="width: 20%"
                         align="center">
          <el-table-column prop="id"
                           label="ID"
                           style="width: 20%"
                           align="center"></el-table-column>
          <el-table-column prop="activity"
                           label="名字"
                           style="width: 20%"
                           align="center"></el-table-column>
        </el-table-column>
        <!-- <el-table-column style="width: 80%"
        align="center">-->
        <el-table-column :label="weekNum"
                         align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.rowSum }}</span>
          </template>
        </el-table-column>
        <el-table-column v-for="(item, index) in dates"
                         :key="index"
                         :label="item.date"
                         align="center">
          <el-table-column :label="item.week"
                           style="width: 10%"
                           align="center">
            <template slot-scope="scope">
              <!--              <span style="margin-left: 10px">{{ scope.row.effort[index] }}</span>-->
              <span v-if="getXLSX">{{scope.row.effort[index]}} - {{getSum(index,scope.row.effort[index])}}</span>
              <el-row v-else>
                <el-col :span="24">
                  <el-input v-model="scope.row.effort[index]"
                            type="number"
                            placeholder="请输入工时"
                            max="16"
                            min="0"
                            @change="inputChange(scope.row.effort,index)"
                            size="small"></el-input>
                  <!--                  </el-col>-->
                  <!--                  <el-col v-if="!isSum(index)" :span="12" class="sum">-->
                  <!--                    / {{getSum(index,scope.row.effort[index])}}-->
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        </el-table-column>
        <!-- </el-table-column> -->
      </el-table>
      <charts v-if="showCharts"
              :tableData="tableData"
              :flag="flag"
              @closedialog="showCharts = false" />
    </el-card>
  </div>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
import charts from "@/components/charts";
import WtButton from "../components/Button";
import dateInfo from "../utils/dateInfo";
export default {
  components: {
    charts,
    WtButton
  },
  data() {
    return {
      flag: 0,
      showCharts: false,
      getXLSX: false,
      chosenDate: "",
      today: "",
      weekNum: "",
      dateList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        firstDayOfWeek: 1,
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            }
          }
        ]
      },
      dates: [
        // {
        //   date: "月/日",
        //   week: "周一"
        // },
      ],
      origEffort: [],
      tableData: [
        {
          id: "P00",
          activity: "请假",
          effort: [1, 2, 3],
          rowSum: ""
        }
      ],
      activities: ["请假", "培训", "其他", "支持电子公司", "项目一", "项目二"],
      activitiesID: ["P01", "P02", "P03", "P04", "P05", "P06"]
    };
  },
  methods: {
    isSum(row) {
      return row == this.tableData.length - 1;
    },
    getSum(col, rowData) {
      let sum = this.tableData[this.tableData.length - 1].effort[col];
      return sum <= 8 ? 0 : Math.round(((sum - 8) * rowData) / sum);
    },
    // *提交
    onSubmit() {
      // console.log("sum:", this.tableData[this.activities.length].effort);
      var isSubmit = false;
      for (i = 0; i < 5; i++) {
        if (
          this.tableData[this.activitiesID.length].effort[i] > 0 &&
          this.tableData[this.activitiesID.length].effort[i] < 8
        ) {
          this.$message.error("一天工时填写范围:8~24");
          this.$message.error(
            "嘿,注意了!!! 星期" +
              (i + 1) +
              "的总工时为" +
              this.tableData[this.activitiesID.length].effort[i] +
              "不符合规范"
          );
          return;
        }
      }
      var effort = [];

      for (var i = 0; i < this.activitiesID.length; i++) {
        for (var j = 0; j < 7; j++) {
          if (this.origEffort[i][j] != this.tableData[i].effort[j]) {
            // console.log("update: ", this.origEffort[i][j], this.tableData[i].effort[j]);
            isSubmit = true;
            var tag;
            if (
              this.origEffort[i][j] == 0 &&
              this.tableData[i].effort[j] != 0
            ) {
              tag = 1;
            } else if (
              this.origEffort[i][j] != 0 &&
              this.tableData[i].effort[j] == 0
            ) {
              tag = -1;
            } else if (
              this.origEffort[i][j] != 0 &&
              this.tableData[i].effort[j] != 0
            ) {
              tag = 0;
            }

            effort.push({
              time: this.dateList[j],
              value: this.tableData[i].effort[j],
              flag: tag,
              projectId: this.activitiesID[i]
            });
          }
        }
      }
      console.log("onSumbit dateList: ", effort);
      if (isSubmit) {
        this.$api.userInfo
          .onsubmitTable({
            userId: this.$store.state.id,
            weeks: dateInfo.getWeekNum(this.chosenDate),
            effort: effort
          })
          .then(response => {
            // console.log("提交表单", response.data);
            if (response.data) {
              this.$message.success("工时表提交成功!");

              for (var i = 0; i < this.activities.length; i++) {
                for (var j = 0; j < 7; j++) {
                  if (this.origEffort[i][j] != this.tableData[i].effort[j]) {
                    this.origEffort[i][j] = this.tableData[i].effort[j];
                  }
                }
              }
            } else {
              this.$message.error("提交失败, 请重新提交");
            }
          })
          .catch(error => {
            this.$message.error("提交失败, 请重新提交");
          });
      }
    },

    // *获取本周的数组，d 为周一的日期 2019-11-17
    resetWeek(d) {
      // d是当前星期一的日期对象
      var date = new Date(Date.parse(d));
      if (date.getDay() != 1) {
        this.chosenDate = dateInfo.getMonDate(d, date.getDay());
      }
      var temp = this.dates;
      var arr = this.chosenDate.split("-");
      var monDaysNum = dateInfo.getMonthDaysNum(arr[0], arr[1]);
      this.dateList = [];
      // console.log("monDaysNum", monDaysNum);
      for (var i = 0; i < 7; i++) {
        if (parseInt(arr[2]) + i <= monDaysNum) {
          temp[i] = {
            date: arr[1] + "月" + (parseInt(arr[2]) + i) + "日",
            week: dateInfo.getDayName(
              arr[0] + "-" + arr[1] + "-" + (parseInt(arr[2]) + i)
            )
          };
        } else {
          //跨月了
          if (parseInt(arr[1]) + 1 <= 12) {
            temp[i] = {
              date:
                parseInt(arr[1]) +
                1 +
                "月" +
                (parseInt(arr[2]) + i - monDaysNum) +
                "日",
              week: dateInfo.getDayName(
                arr[0] +
                  "-" +
                  (parseInt(arr[1]) + 1) +
                  "-" +
                  (parseInt(arr[2]) + i - monDaysNum)
              )
            };
          } else {
            // 跨年了
            temp[i] = {
              date: "1" + "月" + (parseInt(arr[2]) + i - monDaysNum) + "日",
              week: dateInfo.getDayName(
                parseInt(arr[0]) +
                  1 +
                  "-" +
                  "01" +
                  "-" +
                  (parseInt(arr[2]) + i - monDaysNum)
              )
            };
          }
        }
        var mon = temp[i].date.split("月")[0];
        var day = temp[i].date.split("月")[1].split("日")[0];
        if (day <= 9) {
          day = "0" + day;
        }
        if (mon <= 9) {
          mon = "0" + mon;
        }
        this.dateList[i] = arr[0] + "-" + mon + "-" + day;
      }
      let flag = false;
      for (var i = 0; i < 6; i++) {
        if (
          this.dateList[i].split("-")[1] > this.dateList[i + 1].split("-")[1]
        ) {
          flag = true;
        }
        if (flag) {
          this.dateList[i + 1] =
            parseInt(this.dateList[i + 1].split("-")[0]) +
            1 +
            "-" +
            this.dateList[i + 1].split("-")[1] +
            "-" +
            this.dateList[i + 1].split("-")[2];
        } else {
          this.dateList[i + 1] =
            parseInt(this.dateList[i + 1].split("-")[0]) +
            "-" +
            this.dateList[i + 1].split("-")[1] +
            "-" +
            this.dateList[i + 1].split("-")[2];
        }
      }
      this.dates = temp;
      // console.log("resetweek", this.dates);
      // console.log("dateList", this.dateList);
    },
    // 输入change时,触发该函数
    inputChange: function(effort, index) {
      if (!effort[index]) {
        effort[index] = 0;
        this.$message.error("输入异常!!");
      }
      var sum = 0;
      for (var i = 0; i < this.tableData.length - 1; i++) {
        sum += parseFloat(this.tableData[i].effort[index]);
      }
      if (effort[index] < 0 || effort[index] > 24 || sum > 24) {
        this.$message.warning("一天工时填写范围:8~24");
        effort[index] = 0;
      } else {
        effort[index] = parseFloat(effort[index]);
        if (effort[index] % 1) {
          if (effort[index] % 1 > 0.5) {
            this.$message.warning("工时的最小单位为0.5");
            effort[index] = parseInt(effort[index]) + 1;
          } else if (effort[index] % 1 < 0.5) {
            this.$message.warning("工时的最小单位为0.5");
            effort[index] = parseInt(effort[index]);
          }
        }
      }
      var temp = [];
      for (var i = 0; i < this.tableData.length; i++) {
        temp[i] = this.tableData[i].effort;
      }
      this.flushTable(temp);
    },
    // pickerchange时,触发该函数
    pickerChange: function() {
      this.flushDate();
      this.$api.userInfo
        .requestActivites()
        .then(response => {
          this.activities = response.data.projectsName;
          // console.log("activities", this.activities, this.activities[1]);
        })
        .catch(error => {
          console.log("error: ", error);
        });
      // console.log("requestWritePageData中参数", this.$store.state.id, this.dateList[0], this.dateList[6]);
      this.$api.userInfo
        .requestWritePageData({
          userId: this.$store.state.id,
          startTime: this.dateList[0],
          endTime: this.dateList[6]
        })
        .then(response => {
          // console.log("pickerChange获得的effort table结构", response.data);
          this.flushTable(response.data.efforts);

          // * save origin Effort
          this.origEffort = response.data.efforts;
          console.log("pickerChange origEffort", this.origEffort);
        })
        .catch(error => {
          console.log("init error: ", error);
        });
    },
    //刷新表头时间数据
    flushDate: function() {
      this.resetWeek(this.chosenDate);
      this.weekNum = "第" + dateInfo.getWeekNum(this.chosenDate) + "周";
    },
    //刷新表格中1. 项目列表 2. Effort内容及求和
    flushTable: function(matrix) {
      //   console.log("before matrix: ", matrix);
      var tempData = [];
      var colSum = [];
      console.log("len: ", this.activities.length);
      for (var i = 0; i < this.activities.length; i++) {
        var rowEffort = [];
        for (var j = 0; j < 7; j++) {
          rowEffort.push(matrix[i][j]);
        }
        tempData.push({
          id: this.activitiesID[i],
          activity: this.activities[i],
          effort: rowEffort,
            rowSum: dateInfo.getSum(rowEffort),
          // rowSum: eval(rowEffort.join("+"))
        });
      }
      for (var i = 0; i < 7; i++) {
        colSum[i] = 0;
        for (var j = 0; j < this.activities.length; j++) {
          colSum[i] += matrix[j][i];
        }
      }
      tempData.push({
        id: "-",
        activity: "Summary",
        effort: colSum,
          rowSum: dateInfo.getSum(colSum),
        // rowSum: eval(colSum.join("+"))
      });

      this.tableData = tempData;
    },

    //以当天时间初始化数据
    initData: function() {
      //获当天时间
      var now = new Date();
      this.chosenDate =
        now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
      this.weekNum =
        "第" +
        String(parseInt(dateInfo.getWeekNum(this.chosenDate)) - 1) +
        "周";
      this.flushDate();
      this.$api.userInfo
        .requestActivites()
        .then(response => {
          this.activities = response.data.projectsName;
          this.activitiesID = response.data.projectsId;
        })
        .catch(error => {
          console.log("error: ", error);
        });
      this.$api.userInfo
        .requestWritePageData({
          userId: this.$store.state.id,
          startTime: this.dateList[0],
          endTime: this.dateList[6]
        })
        .then(response => {
          // * console.log("获得的effort table结构", response.data);
          this.flushTable(response.data.efforts);

          // * save origin Effort
          this.origEffort = response.data.efforts;
          console.log("init origEffort", this.origEffort);
          // for (var i = 0; i < this.activities.length; i++) {
          //   this.origEffort[i] = response.data.efforts[i];
          // }
        })
        .catch(error => {
          console.log("init error: ", error);
        });
    },
    //定义导出Excel表格事件
    exportExcel: function() {
      this.getXLSX = true;
      setTimeout(() => {
        /* 从表生成工作簿对象 */
        var wb = XLSX.utils.table_to_book(document.querySelector("#table"));
        /* 获取二进制字符串作为输出 */
        var wbout = XLSX.write(wb, {
          bookType: "xlsx",
          bookSST: true,
          type: "array"
        });
        try {
          FileSaver.saveAs(
            //Blob 对象表示一个不可变、原始数据的类文件对象。
            //Blob 表示的不一定是JavaScript原生格式的数据。
            //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
            //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
            new Blob([wbout], { type: "application/octet-stream" }),
            //设置导出文件名称
            "工时填写.xlsx"
          );
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
        }
        this.getXLSX = false;
        return wbout;
      }, 1000);
    },
    pieChart: function() {
      var pieData = [];
      var pieChartData = [];
      for (var i = 0; i < this.tableData.length - 1; i++) {
        pieData.push(this.tableData[i].activity);
        pieChartData.push({
          value: this.tableData[i].rowSum,
          name: this.tableData[i].activity
        });
      }
      this.drawPieChart(pieData, pieChartData);
    },
    drawPieChart(data, items) {
      this.chartPie = echarts.init(document.getElementById("chartPie"));
      this.chartPie.setOption({
        title: {
          text: "工时填写",
          x: "center"
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          orient: "vertical",
          left: "left",
          data: data
        },
        series: [
          {
            name: "访问来源",
            type: "pie",
            radius: "55%",
            center: ["50%", "60%"],
            data: items,
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            }
          }
        ]
      });
    }
  },
  created: function() {},
  mounted: function() {
    this.initData();
  }
};
</script>

<style lang="less" scoped>
.block {
  margin-bottom: 30px;
  margin-top: 25px;
}
#table-block {
  width: 85%;
  margin: 50px auto;
  border-radius: 25px;
  padding: 0px 10px;
}
#table {
  margin-top: 20px;
}
#table-head-block {
  width: 200px;
  font-size: 20px;
  margin: 20px auto;
  border-radius: 25px;
}
/deep/.el-input__inner {
  border: 0px solid #dcdfe6;
  width: 100%;
}
.sum {
  height: 32px;
  line-height: 32px;
  color: #409eff;
}

.more-btn {
  width: 100%;
  text-align: center;
}
</style>
